package cn.com.dashihui.api.service;

import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.LinkedBlockingQueue;

import com.jfinal.aop.Duang;
import com.jfinal.json.FastJson;
import com.jfinal.kit.JsonKit;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;

import cn.com.dashihui.api.Queue.OrderQueue;
import cn.com.dashihui.api.Queue.SingleQueue;
import cn.com.dashihui.api.common.RedisKey;
import cn.com.dashihui.api.dao.OrderG;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

public class OrderGDellService implements Callable<Boolean> {
	
	private Cache orderCache = Redis.use("OrderG");
	
	private LinkedBlockingQueue<String> queue = SingleQueue.getInstance();
	private GroupRedisService grservice = Duang.duang(GroupRedisService.class);
	
	@Override
	public Boolean call() throws Exception {
		try {
			for ( ;; ) {
				if ( queue.size() == 0 ) {
					break;
				}
				String id = queue.poll();
				//得到 支付成功的order队列
				Jedis jedis = orderCache.getJedis();
				jedis.watch(RedisKey.Key.QUEUE+id);
				OrderQueue orders = FastJson.getJson().parse(jedis.get(RedisKey.Key.QUEUE+id), OrderQueue.class);
				Transaction tx = jedis.multi();
				
				while( orders.size()>0 ){
					OrderG order = orders.poll();
					dealQueue(id, jedis, orders, tx, order);
				}
			}
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	private void dealQueue(String id, Jedis jedis, OrderQueue orders, Transaction tx, OrderG order) {
		tx.set(RedisKey.Key.QUEUE+id, JsonKit.toJson(orders));
		List<Object> exec = tx.exec();
		if( exec == null || exec.isEmpty() ){
			//失败   orders  不是最新数据
			jedis.resetState();
			tx = jedis.multi();
			dealQueue( id,  jedis,  orders,  tx,  order) ;
		} else {
			System.out.println("得到order"+order);
//						处理团购 
			grservice.dealGroupOrderG(order);
		}
	}

}
